﻿using System;

namespace PSE.Framework.Messaging
{
    /// <summary>
    /// Performs operations on System.String instances that contain queue path information.
    /// </summary>
    public class MsmqPathUtil
    {
        #region Constants
        const string FORMATNAME = @"FormatName:";
        const string FORMATNAME_DIRECT_OS = @"FormatName:Direct=OS:";
        const string FORMATNAME_DIRECT_TCP = @"FormatName:Direct=TCP:";
        #endregion        

        #region Methods
        /// <summary>
        /// Gets the format name from the given path.
        /// </summary>
        /// <param name="path">The queue's path.</param>
        /// <returns></returns>
        public string GetFormatName(string path)
        {            
            string ret;
            int idxEndFormatName;

            idxEndFormatName = path.IndexOf(FORMATNAME, StringComparison.OrdinalIgnoreCase) + FORMATNAME.Length;
            ret = path.Substring(idxEndFormatName);

            return ret;
        }

        /// <summary>
        /// Gets the queue's name from the given path and machine name.
        /// </summary>
        /// <param name="path">The queue's path.</param>
        /// <param name="machineName">The machine name.</param>
        /// <returns></returns>
        public string GetQueueName(string path, string machineName)
        {
            string ret;
            int idxStartQueueName;
            if (path.IndexOf(FORMATNAME_DIRECT_OS) > 0)
            {
                idxStartQueueName = path.IndexOf(FORMATNAME_DIRECT_OS, StringComparison.OrdinalIgnoreCase) + FORMATNAME_DIRECT_OS.Length + machineName.Length;
                ret = path.Substring(idxStartQueueName);
            }
            else
            {
                idxStartQueueName = path.IndexOf(FORMATNAME_DIRECT_TCP, StringComparison.OrdinalIgnoreCase) + FORMATNAME_DIRECT_TCP.Length + machineName.Length;
                ret = path.Substring(idxStartQueueName + 1);
            }

            return ret;
        }

        /// <summary>
        /// Gets the machine name from the given path.
        /// </summary>
        /// <param name="path">The queue's path.</param>
        /// <returns></returns>
        public string GetMachineName(string path)
        {
            string ret;
            int idxStartQueueName;
            int idxEndMachineName;

            idxStartQueueName = path.IndexOf(FORMATNAME_DIRECT_OS, StringComparison.OrdinalIgnoreCase) + FORMATNAME_DIRECT_OS.Length;
            idxEndMachineName = path.IndexOf(@"\", idxStartQueueName);
            ret = path.Substring(idxStartQueueName, idxEndMachineName - idxStartQueueName);

            return ret;
        }
        #endregion        
    }
}
